package 网络原理3TCP_IP.简单的网络计算器;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class CalcClient {
    private DatagramSocket socket = null;
    private String serverIP;
    private int serverPort;

    public CalcClient(String serverIP, int serverPort) throws SocketException {
        this.serverIP = serverIP;
        this.serverPort = serverPort;
        this.socket = new DatagramSocket();
    }
    public void start() throws IOException {
        System.out.println("客户端启动!!!");
        Scanner scanner = new Scanner(System.in);
        while(true){
            System.out.println("请输入操作数a:>");
            int a = scanner.nextInt();
            System.out.println("请输入操作数b:>");
            int b = scanner.nextInt();
            System.out.println("请输入运算符:>");
            String s = scanner.next();
            //发送请求
            String request = a + ";" + b + ";" + s;
            DatagramPacket requestPacket = new DatagramPacket(request.getBytes(),request.getBytes().length,
                    InetAddress.getByName(this.serverIP),this.serverPort);
            socket.send(requestPacket);
            //接受响应
            DatagramPacket responsePacket = new DatagramPacket(new byte[4096],4096);
            socket.receive(responsePacket);
            //打印日志
            String response = new String(responsePacket.getData(),0,responsePacket.getLength());
            String log = String.format("req: %s;resp: %s",request,response);
            System.out.println(log);
        }
    }

    public static void main(String[] args) throws IOException {
        CalcClient client = new CalcClient("127.0.0.1",9090);
        client.start();
    }
}
